package com.hengpeng.itfinoss.service.stm.impl;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.admin.SmsLogRequest;
import com.hengpeng.itfinbase.message.admin.SmsResendRequest;
import com.hengpeng.itfinbase.persist.SmsLog;
import com.hengpeng.itfinbase.persist.SmsLog.SmsLogState;
import com.hengpeng.itfinbase.persist.SmsLog.SmsLogTransType;
import com.hengpeng.itfinbase.persist.SmsLog.SmsSendState;
import com.hengpeng.itfinbase.persist.SmsPartner;
import com.hengpeng.itfinbase.persist.SmsPartner.SmsPartnerStatus;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.service.stm.SmsService;

/**
 * 短信日志服务接口实现
 * @author lanmingming
 */

@Service
@Lazy
public class SmsServiceImpl implements SmsService
{

	/**
	 * 短信接口用户名
	 */
	public static final String SMSPORT_USERNAME = "smsport_username";

	/**
	 * 短信接口密码
	 */
	public static final String SMSPORT_PWD = "smsport_pwd";

	@Autowired
	private ServiceFactory serviceFactory;

	@Override
	public ServiceResult<List<SmsLog>> selectSmsLogPage(String content, String mobile, Integer retryCount,
			Date sendTime1, Date sendTime2, SmsLogState state, Date successTime1, Date successTime2, SmsLogTransType type,
			String userId, int indexPage, int pageSize, OrderType order, String orderField)
	{
		DynamicQuery query = new DynamicQuery(SmsLog.class);
		if (content != null && content.trim().length() > 0)
			query.like("content", "%" + content + "%");
		if (mobile != null && mobile.trim().length() > 0)
			query.eq("mobile", mobile);
		if (retryCount != null && retryCount > 0)
			query.eq("retryCount", retryCount);
		if (sendTime1 != null && sendTime2 != null && sendTime1.toString().trim().length() > 0
				&& sendTime2.toString().trim().length() > 0)
			query.between("sendTime", sendTime1, sendTime2);
		if (state != null && state.getText().trim().length() > 0)
			query.eq("state", state);
		if (successTime1 != null && successTime2 != null && successTime1.toString().trim().length() > 0
				&& successTime1.toString().trim().length() > 0)
			query.between("successTime", successTime1, successTime2);
		if (type != null && type.getText().trim().length() > 0)
			query.eq("type", type);
		if (userId != null && userId.trim().length() > 0)
			query.eq("userId", userId);
		if (order != null)
		{
			if (order.name().equalsIgnoreCase("asc"))
			{
				query.asc(orderField);
			}
			else
			{
				query.desc(orderField);
			}
		}
		query.setIsSearchTotalCount(true);
		query.setPageIndex(indexPage);
		query.setPageSize(pageSize);
		QueryResult<SmsLog> requery = serviceFactory.getPersistService().findWithPage(SmsLog.class, query);
		ServiceResult<List<SmsLog>> result = new ServiceResult<List<SmsLog>>(requery.getResults());
		result.setReturnListSize((int) requery.getTotalCount());
		return result;
	}

	@Override
	public ResponseMessage smsReSend(String ids)
	{
		SmsResendRequest request = new SmsResendRequest();
		request.setIds(ids);
		//request.setTransType(TransCodeConstants.AdminTransCode.STM_RESEND_MESSAGE);
		return serviceFactory.getRemoteService().remoteTrans(request);
	}

	@Override
	public boolean smsImmediatelySend(String mobile, String content, SmsSendState state, SmsLogTransType type)
	{
		// 发送即时短信
		SmsPartner partner = null;
		List<SmsPartner> list = serviceFactory.getPersistService().list(SmsPartner.class);
		if (list != null && list.size() > 0)
		{
			partner = list.get(0);
		}
		if (partner == null)
		{
			return false;
		}
		SmsLogRequest request = new SmsLogRequest();
		Integer priority = partner.getPriority();
		String sendstate = state.name();
		Integer smsType = type.getValue();
		request.setIsfrist("0");
		request.setMobile(mobile);
		request.setContent(content);
		request.setPriority(priority.toString());
		request.setSendstate(sendstate);
		request.setSmsType(smsType.toString());
		request.setUserId(partner.getId().toString());
	//	request.setTransType(TransCodeConstants.AdminTransCode.STM_SEND_MESSAGE);
		ResponseMessage response = new ResponseMessage();
		try
		{
			response = serviceFactory.getRemoteService().remoteTrans(request);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			response.setReturnObject(false);
		}
		if (Constant.TRANSACTION_RESPONSE_CODE_SUCCESS.equals(response.getRespCode()))
			return true;
		return false;
	}

	public QueryResult<SmsPartner> findSmsPartnerWithPage(Long id, String name, Integer pageIndex, Integer pageSize,
			LinkedHashMap<String, OrderType> sortMap)
	{
		DynamicQuery query = new DynamicQuery(SmsPartner.class);
		if (id != null)
		{
			query.eq("id", id);
		}
		if (!StringUtils.isEmpty(name))
		{
			query.like("name", "%" + name + "%");
		}
		query.setPageIndex(pageIndex);
		query.setPageSize(pageSize);
		if (sortMap != null)
		{
			for (Entry<String, OrderType> entry : sortMap.entrySet())
			{
				if (entry.getValue() == OrderType.DESC)
				{
					query.desc(entry.getKey());
				}
				else
				{
					query.asc(entry.getKey());
				}
			}
		}
		else
		{
			query.asc("id");
		}
		return serviceFactory.getPersistService().findWithPage(SmsPartner.class, query);
	}

	public List<SmsPartner> findAllOpen()
	{
		DynamicQuery query = new DynamicQuery(SmsPartner.class);
		query.eq("status", SmsPartnerStatus.OPEN);
		return serviceFactory.getPersistService().find(SmsPartner.class, query);
	}
}
